import React, { ChangeEvent } from "react";
import Square from "./squre";
import Drap from "./drap";
import { positionsStore, chartsStore } from "./store";
import Charts from "./charte";
import TextArea from "antd/lib/input/TextArea";

export default class Page4 extends React.Component {
  public state = {
    activeDrags: 0,
    deltaPosition: {
      x: 0, y: 0
    },
    controlledPosition: {
      x: 0, y: 0
    }
  }

  public componentDidMount() {
    positionsStore.scan((arr: any, value: { key: any, value: boolean, name: string }) => {
      arr[value.name] = value
      return arr
    }, {}).debounceTime(2000).map(arr => {
      console.log('arr', arr)
      return Object.keys(arr).map(key => arr[key]).filter(v => v.value).map(v => v.key)
    }).map((positons: Array<Array<[number, number]>>) => {
      console.log('positons', positons)
      const leftTop = [Math.min(...positons.map(positon => positon[0][0])), Math.min(...positons.map(positon => positon[0][1]))]
      const rightBottom = [Math.max(...positons.map(positon => positon[3][0])), Math.max(...positons.map(positon => positon[3][1]))]
      return { leftTop, width: rightBottom[0] - leftTop[0], height: rightBottom[1] - leftTop[1] }
    }).subscribe(({ leftTop, width, height }) => {
      console.log('p', { leftTop, width, height })
      chartsStore.next({ leftTop, width, height })
    })
  }

  public onStart = (...args: any[]) => {
    console.log(args)
    this.setState({ activeDrags: ++this.state.activeDrags });
  }

  public onStop = (...args: any[]) => {
    console.log(args)
    this.setState({})
    this.setState({ activeDrags: --this.state.activeDrags });
  }


  public onControlledDrag = (e: any, position: any) => {
    const { x, y } = position;
    this.setState({ controlledPosition: { x, y } });
  }

  public handleDrag = (e: any, ui: any) => {
    const { x, y } = this.state.deltaPosition;
    this.setState({
      deltaPosition: {
        x: x + ui.deltaX,
        y: y + ui.deltaY,
      }
    });
  }

  public render() {
    return (
      <div style={{ display: 'flex' }}>
        <div style={{ width: 1000, height: 500, background: 'red', left: 100, position: 'relative', margin: '0 auto' }}>
          {this.renderSquire()}
          <Charts />
          <Drap />
        </div>
        <div >
          <TextArea onChange={(e: ChangeEvent<HTMLTextAreaElement>) => localStorage.setItem('parse', e.target.value)} />
        </div>
      </div>
    )
  }

  public renderSquire() {
    const squires = []
    for (let i = 0; i < 10; i += 1) {
      for (let j = 0; j < 10; j += 1) {
        squires.push(<Square x={i} y={j} />)
      }
    }
    return squires
  }
}